#include "../lib/viewer.hpp"
#include "../../video.hpp"
#include <iostream>
#include <pipc.hpp>

using namespace std;

Viewer::Viewer(pland::SharedDQueue qB, pland::SharedDQueue qG, pland::SharedDQueue qR)
{
    qB_ = qB;
    qR_ = qR;
    qG_ = qG;

}

void Viewer::start()
{
    pipc::Pipc* settings = pipc::Pipc::Instance();
    while(true)
    {
        boost::this_thread::interruption_point();
        boost::thread bt(boost::bind(&Viewer::decodePNG, this, qB_->pop(), B));
        boost::thread gt(boost::bind(&Viewer::decodePNG, this, qG_->pop(), G));
        boost::thread rt(boost::bind(&Viewer::decodePNG, this, qR_->pop(), R));
        bt.join();
        gt.join();
        rt.join();
        if(b_.rows == 0 || r_.rows == 0 || g_.rows == 0)
        {
            continue;
        }
        pipc::Record res = settings->getValue("capture.resolution");
        std::vector<cv::Mat> channels;
        channels.push_back(b_);
        channels.push_back(g_);
        channels.push_back(r_);
        cv::Mat final;
        cv:merge(channels, final);
        cv::putText(final, std::string("Resolution: ") + res.data, cvPoint(30,30), cv::FONT_HERSHEY_COMPLEX_SMALL, 0.8, cvScalar(255,0,0), 1, CV_AA);
        res = settings->getValue("motion.relarea");
        cv::putText(final, std::string("Motion area: ") + res.data, cvPoint(30,60), cv::FONT_HERSHEY_COMPLEX_SMALL, 0.8, cvScalar(255,0,0), 1, CV_AA);
        cv::imshow("Viewer", final);
        cv::waitKey(1);
    }
}

void Viewer::decodePNG(pland::SharedData source, CHANNEL c)
{
    if(isPNG((char*)source->get_data()))
    {
        cout << "Bad signature" << endl;
        cv::Mat img;
        if(c == B)
            b_ = img;
        if(c == G)
            g_ = img;
        if(c == R)
            r_ = img;
    }
    try
    {
        cv::Mat png(1, source->get_header()->size, CV_8U, source->get_data());
        cv::Mat img = imdecode(png, CV_LOAD_IMAGE_GRAYSCALE);
        if(c == B)
            b_ = img;
        if(c == G)
            g_ = img;
        if(c == R)
            r_ = img;
    }
    catch(cv::Exception &e)
    {
        cout << "Bad Decoding" << endl;
        cv::Mat img;
        if(c == B)
            b_ = img;
        if(c == G)
            g_ = img;
        if(c == R)
            r_ = img;
    }
}
